import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_eve_plugin/constants/constant.dart';
import 'package:flutter_eve_plugin/constants/localizations.dart';
import 'package:flutter_eve_plugin/pages/main/actions.dart';
import 'package:flutter_eve_plugin/plugin/actions.dart';
import 'package:flutter_eve_plugin/plugin/main.dart';
import 'package:flutter_eve_plugin/route/main.dart';
import 'package:flutter_eve_plugin/store/main.dart';
import 'package:flutter_eve_plugin/utils/print_util.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:redux/redux.dart';
import 'package:flutter_localizations/flutter_localizations.dart';

class App extends StatefulWidget {
  final Store<AppState> store;
  final String route;

  App({Key key, this.store, this.route}) : super(key: key);

  @override
  _AppState createState() => _AppState();
}

class _AppState extends State<App> {
  @override
  void initState() {
    super.initState();
    eventChannel
        .receiveBroadcastStream()
        .listen(PluginEve.onEvent, onError: PluginEve.onError);
    if (Platform.isIOS) {
      receiveRoute();
    }
  }

  @override
  Widget build(BuildContext context) {
    initPushName = widget.route;
    logDebugPrint('initPushName $initPushName');
    return StoreProvider<AppState>(
      store: widget.store,
      child: MaterialApp(
        theme: ThemeData(platform: TargetPlatform.iOS),
        localizationsDelegates: [
          ChineseCupertinoLocalizations.delegate,
          DefaultCupertinoLocalizations.delegate,
          GlobalMaterialLocalizations.delegate,
          GlobalWidgetsLocalizations.delegate,
        ],
        supportedLocales: [
          const Locale('zh', 'CH'),
        ],
        navigatorKey: navigatorKey,
        // initialRoute: widget.route,
        initialRoute: RouteConstant.DebugMainPage,
        routes: routes(context),
        onGenerateRoute: genRoute,
        navigatorObservers: [
          NavObserver(),
        ],
      ),
    );
  }

  Route genRoute(RouteSettings setting) {
    return PageRouteBuilder(
      pageBuilder: (context, _, __) {
        return findRouteWidget(context, setting.name);
      },
    );
  }
}

class NavObserver extends NavigatorObserver {
  @override
  void didPush(Route route, Route previousRoute) {
    logDebugPrint('push ${route.settings.name}');
  }

  @override
  void didPop(Route route, Route previousRoute) {
    logDebugPrint('pop ${route.settings.name}');
    if (initPushName == route.settings.name) {
      goBackNative();
    }
  }

  @override
  void didReplace({Route newRoute, Route oldRoute}) {
    logDebugPrint('replace ${newRoute.settings.name}');
  }
}
